<?php
class SmsController extends Controller{

	public $smsUsername;
	public $smsPassword;
	private $_debug=false;

	public function actionIndex(){
		$this->_debug=isset($_POST['smsdebug']);
		$this->actionNotify();
		
	}

	public function actionNotify(){
		if(isset($_POST['username']) && isset($_POST['password'])
		&& $_POST['username']===$this->smsUsername && $_POST['password']===$this->smsPassword){
			$rawMessage=new RawSmsMessage();
			$rawMessage->notificationType=$_POST['notificationType'];
			$rawMessage->id=$_POST['id'];
			$rawMessage->originator=$_POST['originator'];
			$rawMessage->recipient=$_POST['recipient'];
			$rawMessage->body=$_POST['body'];
			$rawMessage->type=$_POST['type'];
			$rawMessage->sentAt=$_POST['sentAt'];
			$rawMessage->receivedAt=$_POST['receivedAt'];
			$rawMessage->notificationType=$_POST['notificationType'];

			$rawMessage->sendFrom=$_SERVER['REMOTE_ADDR'];
			$rawMessage->sendServerTime=new CDbExpression('NOW()');
			$rawMessage->processed=0;
			$rawMessage->messageValid=0;

			$processMethod='process'.ucfirst($rawMessage->notificationType);

			$rawMessage->save();

			if(method_exists($this,$processMethod)){
				$this->$processMethod($rawMessage);
			}
		}
		

		Yii::app()->end();
	}

	private function processMessageReceived($rawMessage){
		$text=$rawMessage->body;
		$params=split(' ',trim($text),3);
		if(count($params)==1){
			$action='vote';
			$target=$params[0];
		}elseif(count($params)==2){
			$action=$this->normalizeAction($params[0]);
			$target=$params[1];
		}

		$message=false;//'Unregnized Command';
		if(!empty($action)){
			$method='message'.ucfirst($action);
			if(method_exists($this,$method)){
				$message=$this->$method($rawMessage,$target);
				
			}
		}
		if(!$this->_debug){
			$message && $message!==true && Yii::app()->sms->sendMessage($rawMessage->originator,$message);
		}else{
			echo '<pre>';
			var_dump($message); 
			var_dump($rawMessage); 
			echo '</pre>';
		}
		$rawMessage->processed=1;		
		$rawMessage->save();
		return $message;

	}

	private function normalizeAction($action){
		$action=strtolower($action);
		$vote=array('v','vote');
		if(in_array($action,$vote)){
			return 'vote';
		}
	$pass=array('p','pass');
		if(in_array($action,$pass)){
			return 'pass';
		}
		return NULL;
	}
	
	private function messagePass($rawMessage,$pass){
		$phone=Yii::app()->sms->normalizePhone($rawMessage->originator);
		$user=User::model()->findByAttributes(array('mobile'=>$phone));
		if($user){
			$user->password= Yii::app()->User->encrypting($pass);
			$user->save();
			$rawMessage->messageValid=1;
			return true;
		}
		return false;
		
	}

	private function messageVote($rawMessage,$voteId){		
		$userId=$this->registerMobileUser($rawMessage->originator);
		if($userId===null){
			return false;
		}
		
		$cafe=CoffeeShop::model()->findByVoteId($voteId);
		if($cafe!==null){
			if(CafeVote::vote($cafe->id,CafeVote::FROM_SMS,$userId,$rawMessage->sendFrom)){
				$message='Thank you for voting for Melbourne Coffee Review’s Top 100 café for 2011.
You have successfully voted for: '.$cafe->name.'.';
				$rawMessage->messageValid=1;
			}else{
				$message=false;//'You can vote only once for '.$cafe->name.'.';
			}
		}else{
			$message='Thanks for the vote, the café '.$voteId." is not on our system. Jump on www.melbournecoffeereview.com and register them now, then vote away!!\n The MCR Crew!";
		}
		return $message;
	}

	private function registerMobileUser($phone){
		$phone=Yii::app()->sms->normalizePhone($phone);
		
		$user=User::model()->findByAttributes(array('mobile'=>$phone));
		if($user!==NULL){
			return $user->id;
		}
		
		$model = new User();
		$model->username=$phone;
		$model->email=$phone.'@vote.melbournecoffeereview.com';
		$model->mobile=$phone;
		$password=strval(rand(10000,99999));
		$model->password = Yii::app()->User->encrypting($password);
		//$model->activkey = '';//Yii::app()->User->encrypting(microtime().$model->password);
		$model->createtime = time();
		$model->lastvisit = ((Yii::app()->User->autoLogin && Yii::app()->User->loginNotActive) ? time() : 0);
		$model->superuser = 0;
		$model->status = User::STATUS_ACTIVE;
		$model->activkey=Yii::app()->User->encrypting(microtime().$model->password);
							

		if ($model->save()){
			$message="Thank you for registering at Melbourne Coffee Review. Your Username: $phone; password: $password. ".
			"You can login to our website at ".'http://' .$_SERVER['HTTP_HOST'];
			Yii::app()->sms->sendMessage($phone,$message);
			
			return $model->id;
		}else{
			return null;
		}
	}
	
	

}